const path = require('path')
const http = require('http')
const https = require('https')
const bodyParser = require('body-parser')
const express = require('express')
const app = new express()
const request = require('request')
const port = process.env.PORT || 2600;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: false
})); //解析post请求数据

app.use(express.static('public'));
app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'views', 'index.html'));
})
const AppID = 'wx8af114e3f3e9c03f';
const AppSecret = '255325a19bd769aec6e3080db6ce3da8';
const redirect_uri = 'http%3a%2f%2flongfor.ele233.com';
const scope = 'snsapi_userinfo';
app.get('/wechat_login', (req, res) => {
  res.redirect('https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + AppID + '&redirect_uri=' + redirect_uri + '&response_type=code&scope=' + scope + '&state=STATE#wechat_redirect');
})
app.get('/user', function (req, res, next) {
  var code = req.query.code; // 第二步：通过code换取网页授权access_token
  request.get({
    url: 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' + AppID + '&secret=' + AppSecret + '&code=' + code + '&grant_type=authorization_code',
  }, function (error, response, body) {
    if (response.statusCode == 200) {
      var data = JSON.parse(body);
      var access_token = data.access_token;
      var openid = data.openid;
      request.get({
        url: 'https://api.weixin.qq.com/sns/userinfo?access_token=' + access_token + '&openid=' + openid + '&lang=zh_CN',
      }, function (error, response, body) {
        if (response.statusCode == 200) {
          var userinfo = JSON.parse(body); // 第四步：根据获取的用户信息进行对应操作
          console.log('获取微信信息成功！');
          res.send({
            name: userinfo.nickname,
            got: true
          });
        } else {
          console.log(response.statusCode);
          res.send({
            name: '',
            got: false
          })
        }
      });
    } else {
      console.log(response.statusCode);
      res.send({
        name: '',
        got: false
      })
    }
  })
});





app.listen(port, (error) => {
  if (error) {
    console.error(error);
  } else {
    console.info('==> Listening on port %s. Open up http://localhost:%s/ in your browser.', port, port);
  }
});
